# -*- coding: utf-8 -*-
"""
DeepSeek AI服务
"""

import time
import os
from typing import List, Dict, Any
from openai import OpenAI
from ai_service_base import AIServiceBase, ModelConfig

class DeepSeekAIService(AIServiceBase):
    """DeepSeek AI服务"""
    
    def __init__(self, config: ModelConfig = None):
        # DeepSeek配置（通过豆包平台）
        if config is None:
            config = ModelConfig(
                id="deepseek-v3-1-250821",
                name="DeepSeek V3",
                provider="deepseek",
                api_key=os.environ.get("DEEPSEEK_API_KEY", "efe908df-5c29-4c32-9116-40dbbf6cbda9"),
                base_url="https://ark.cn-beijing.volces.com/api/v3",
                max_tokens=1000,
                temperature=0.7
            )
        
        super().__init__(config)
        
        # 初始化OpenAI客户端（DeepSeek使用OpenAI兼容API）
        self.client = OpenAI(
            base_url=self.config.base_url,
            api_key=self.config.api_key
        )
    
    def chat_completion(self, messages: List[Dict[str, str]]) -> str:
        """同步对话完成"""
        try:
            start_time = time.time()
            
            response = self.client.chat.completions.create(
                model=self.config.id,
                messages=messages,
                temperature=self.config.temperature,
                max_tokens=self.config.max_tokens
            )
            
            content = response.choices[0].message.content
            elapsed_time = time.time() - start_time
            
            print(f"DeepSeek API调用成功，耗时 {elapsed_time:.2f}s")
            print(f"回复内容长度: {len(content)} 字符")
            
            return content
            
        except Exception as e:
            error_msg = f"DeepSeek API调用失败: {str(e)}"
            print(f"错误: {error_msg}")
            return f"抱歉，DeepSeek服务暂时不可用"
    
    async def async_chat_completion(self, messages: List[Dict[str, str]]) -> str:
        """异步对话完成"""
        # 简单起见，先使用同步版本
        return self.chat_completion(messages)
    
    def test_connection(self) -> bool:
        """测试API连接"""
        try:
            # 检查API密钥是否配置
            if not self.config.api_key:
                print("DeepSeek API密钥未配置")
                return False
                
            test_messages = [
                {"role": "user", "content": "你好，请回复'连接成功'"}
            ]
            
            response = self.chat_completion(test_messages)
            return "连接成功" in response or len(response) > 0
            
        except Exception as e:
            print(f"DeepSeek连接测试失败: {e}")
            return False


def test_deepseek_service():
    """测试DeepSeek服务"""
    print("开始测试DeepSeek AI服务...")
    
    service = DeepSeekAIService()
    
    # 测试连接
    if service.test_connection():
        print("DeepSeek API连接成功!")
        
        # 测试对话
        messages = [
            {"role": "user", "content": "你是谁？请简单介绍一下自己。"}
        ]
        
        response = service.chat_completion(messages)
        print(f"\nAI回复:\n{response}")
        
    else:
        print("DeepSeek API连接失败!")


if __name__ == "__main__":
    test_deepseek_service()